//
//  ImageToController.m
//  diaoyuren
//
//  Created by 钓鱼人 on 16/3/4.
//  Copyright © 2016年 game. All rights reserved.
#import "ImageToController.h"
#import "SelectNavView.h"
#import "TZImagePickerController.h"
#import "UIView+Layout.h"
#import "TZImageManager.h"
#import "TZAssetModel.h"
#import "AFHTTPRequestOperationManager.h"
#import "AFURLSessionManager.h"

#define XXXDDD 10
#define WWWWW  (SCREEN_WIDTH-XXXDDD*5)/4

@interface ImageToController ()<TZImagePickerControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic,strong) SelectNavView *naV;
@property (nonatomic,strong) UIScrollView *scrollView;
@property (nonatomic,strong) NSMutableArray *imagess;
@property (nonatomic,strong) UILabel *tipLable;
@property (nonatomic,strong) NSMutableArray *imageDataAry;
@property (nonatomic,strong) NSData *imageData;
@property (nonatomic,strong) NSString *filedPath;
@property (nonatomic,strong) NSMutableArray *filedImgAry;
@property (nonatomic,assign) NSInteger upCount;
@property (nonatomic,strong) NSMutableDictionary *dic;
@end

@implementation ImageToController
-(NSMutableDictionary *)dic{
    if (!_dic) {
        _dic = [NSMutableDictionary dictionary];
    }
    return _dic;
}

-(NSMutableArray *)filedImgAry{
    
    if (!_filedImgAry) {
        _filedImgAry = [NSMutableArray array];
    }
    return _filedImgAry;
}

-(NSMutableArray *)imageDataAry{
    if (!_imageDataAry) {
        _imageDataAry = [NSMutableArray array];
    }
    return _imageDataAry;
}

-(UIScrollView *)scrollView{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
        [self.view addSubview:_scrollView];
    }
    return _scrollView;
}

-(NSMutableArray *)imagess{
    if (!_imagess) {
        _imagess  = [NSMutableArray array];
    }
    return _imagess;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.app.myTabBar.tabBar.hidden = YES;
    self.navigationController.navigationBar.hidden = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self CreatNavView];
}
-(void)CreatNavView{
    self.naV = [[SelectNavView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
    self.naV.titile.text = @"传照片";
    self.naV.share.titleLabel.font = font(SCREEN_WIDTH*0.05);
    [self.naV.share setTitle:@"提交" forState:UIControlStateNormal];
    self.naV.share.y = 21;
    self.naV.share.x = SCREEN_WIDTH - 60;
    [self.view addSubview:self.naV];
    [self.naV.bacBtn addTarget:self action:@selector(Back) forControlEvents:UIControlEventTouchUpInside];
    
    [self.naV.share addTarget:self action:@selector(Tijiao) forControlEvents:UIControlEventTouchUpInside];
}
-(void)Back{
    
    if (self.imagess.count==0) {
        [self.navigationController popViewControllerAnimated:YES];

    }else{
    
    UIAlertController *aler = [UIAlertController alertControllerWithTitle:nil message:@"是否保存草稿?" preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *ToPhone = [UIAlertAction actionWithTitle:@"保存" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self Edit];
    }];
    
    UIAlertAction *ToImage = [UIAlertAction actionWithTitle:@"不保存" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
       
        [self.navigationController popViewControllerAnimated:YES];
        
    }];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    [aler addAction:ToPhone];
    [aler addAction:ToImage];
    [aler addAction:cancel];
    [self presentViewController:aler animated:YES completion:nil];
   
    }
}

-(void)Edit{
   
    NSString *name = @"上传钓场相片[照片]";
    if (self.isyujudian) {
        name = @"上传渔具店相片[照片]";
      
    }
    
    NSDictionary *dic = @{
                          @"time":[Manager AchiveNowTime],
                          @"images":self.imageDataAry,
                          @"name":name,
                          @"type":@"DcUpImage",
                          @"text":@"",
                          @"Id":self.dId,
                          @"isyujud":[NSString stringWithFormat:@"%d",self.isyujudian],
                          };
    
    self.filedImgAry = [NSMutableArray arrayWithContentsOfFile:[Manager editeFilePath]];
    
    [self.filedImgAry insertObject:dic atIndex:0];
    
    [self.filedImgAry writeToFile:[Manager editeFilePath] atomically:YES];
    
    [self.imageDataAry removeAllObjects];
    if ([_deleget respondsToSelector:@selector(GetToEdit)]) {
        [self.deleget GetToEdit];
    }
    
    [self.navigationController popViewControllerAnimated:YES];

}


-(void)Tijiao{

        [self.navigationController popViewControllerAnimated:YES];
    
    if (self.imageDataAry.count!=0) {
        [[Manager sharedManager]RequestWhithURL:GetFormhash AndParameter:nil AndCompletionType:^(id responseObject, DIEError *error) {
            
            if ([responseObject[@"status"] isEqualToString:@"SUCCESS"]) {
                
                
                for (int i=0; i<self.imageDataAry.count; i++) {
                    
                     [self PostImageWhithFormhash:responseObject[@"data"][@"formhash"] WhithImageData:self.imageDataAry[i] AndName:[NSString stringWithFormat:@"%d.jpg",i+1]];
                }

            }
        }];

    }
    
    self.isAnew = NO;
}

-(void)PostImageWhithFormhash:(NSString *)formhash WhithImageData:(NSData *)imageData AndName:(NSString *)name{

//    NSLog(@"%@",self.imageData);
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    NSString *url = islanUploadImage;
    if (self.isyujudian) {
        url = dianpuUploadImage;
    }

   AFHTTPRequestOperation *operation = [manager POST:url parameters:@{@"formhash":formhash,@"id":self.dId,@"type":@"1"} constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        [formData appendPartWithFileData:imageData name:@"Filedata" fileName:name mimeType:@"application/octet-stream"];
        
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
  
        if ([responseObject[@"status"] isEqualToString:@"SUCCESS"]) {
            
            self.upCount += 1;

        }else{
        
            [self Edit];
            if ([self.deleget respondsToSelector:@selector(upLoadfailure)]) {
                
                [self.deleget upLoadfailure]; // 通知执行协议方法
            }
        }

        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [self Edit];
        if ([self.deleget respondsToSelector:@selector(upLoadfailure)]) {
            
            [self.deleget upLoadfailure]; // 通知执行协议方法
        }

    }];
    
    
    [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
        
        float p = (float)totalBytesWritten / totalBytesExpectedToWrite;
       
        [self.dic setValue:[NSString stringWithFormat:@"%f",p] forKey:name];
    
       __block CGFloat  ffff ;
        [self.dic enumerateKeysAndObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            
            ffff += [obj floatValue];
            
        }];

        
        if ([self.deleget respondsToSelector:@selector(upLoadeImageProgress:)]) {
            
            [self.deleget upLoadeImageProgress:(ffff/self.imageDataAry.count)]; // 通知执行协议方法
        }

    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    /**
     *  程序一进来就调此方法  目的是 一进来就建立了 添加 这个Btn
     */
    [self CretUi];
}

#pragma mark--在草稿箱中点击了修改调用方法
-(void)setEditDic:(NSDictionary *)editDic{
    _editDic = editDic;
    
    [self.imageDataAry addObjectsFromArray:_editDic[@"images"]];
    
        for (NSData *imagedta in _editDic[@"images"]) {
    
            UIImage *image = [UIImage imageWithData:imagedta];
    
            [self.imagess addObject:image];
            
        }

        [self CretUi];
}

#pragma mark--在草稿箱中点重发了
-(void)setIsAnew:(BOOL)isAnew{
    _isAnew = isAnew;
    
    if (_isAnew) {
        
        [self Tijiao];
    }
}

#pragma mark TZImagePickerControllerDelegate
// 用户点击了取消
- (void)imagePickerControllerDidCancel:(TZImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

// 用户选择好了图片，如果assets非空，则用户选择了原图。
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets{
    
    [self.imagess addObjectsFromArray:photos];
        [self CretUi];
    
//    
//     [UIImageJPEGRepresentation([Manager imageByScalingToMaxSize:self.imagess[0] WhithMAXWIdth:800],0.8) writeToFile:@"/Users/diaoyuren/Desktop/压缩前.jpg" atomically:YES];
    
    for (UIImage *portraitImg in photos) {
        
        if (portraitImg != nil) { //当图片不为空时显示图片并保存图片
          
            UIImage *image = [Manager imageCompressForWidth:portraitImg targetWidth:800];
            
//            [UIImageJPEGRepresentation(image,0.8) writeToFile:@"/Users/Shanancheng/Desktop/shangchuan.jpg" atomically:YES];
            
            [self.imageDataAry addObject:UIImageJPEGRepresentation(image,0.8)];
        }
    }
    
    
    self.imageData = [NSKeyedArchiver archivedDataWithRootObject:self.imageDataAry];
}


-(void)CretUi{

    [self.scrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    NSInteger count = self.imagess.count;
    
    if (count<9) {
        count = self.imagess.count+1;
    }

    for (int i= 0; i<count; i++) {
        
        CGFloat row = i%4;
        CGFloat lod = i/4;
               
        CGFloat xx = XXXDDD+(XXXDDD+WWWWW)*row;
        CGFloat yy = XXXDDD +(XXXDDD+WWWWW)*lod;
        
        UIButton *imageView = [UIButton buttonWithType:UIButtonTypeCustom];
        
        imageView.frame = CGRectMake(xx, yy, WWWWW, WWWWW);
        
        imageView.tag = i+10000;
        
        imageView.imageView.contentMode  = UIViewContentModeScaleAspectFill;

        if (i<self.imagess.count) {

            [imageView setImage:self.imagess[i] forState:UIControlStateNormal];
            
//                [UIImagePNGRepresentation(self.imagess[i]) writeToFile:@"/Users/diaoyuren/Desktop/未处理.png" atomically:YES];

            UIButton *shanchu = [UIButton buttonWithType:UIButtonTypeCustom];

            shanchu.frame = CGRectMake(WWWWW-25, 0, 25, 25);
            shanchu.tag  = imageView.tag + 100;
            
            [shanchu setImage:[UIImage imageNamed:@"delete_pic"] forState:UIControlStateNormal];
            [imageView addSubview:shanchu];
            
            [shanchu addTarget:self action:@selector(shanchu:) forControlEvents:UIControlEventTouchUpInside];
            
        }else{
        
            
            [imageView setImage:[UIImage imageNamed:@"add_pic"] forState:UIControlStateNormal];
            
            [imageView addTarget:self action:@selector(AddImage) forControlEvents:UIControlEventTouchUpInside];
        }
        
        [self.scrollView addSubview:imageView];
    }

}

-(void)shanchu:(UIButton *)btn{

    NSInteger count = self.imagess.count;
    [self.imagess removeObjectAtIndex:btn.tag-100-10000];
    
    UIButton *bbb = [self.view viewWithTag:btn.tag-100];
    
    [bbb removeFromSuperview];
    
    for (int i=(int)btn.tag-100-10000+1; i<count+1; i++) {
 
        UIButton *tttt = [self.view viewWithTag:i+10000];
    
        tttt.tag -= 1;

           UIButton *shan = [self.view viewWithTag:i+10000+100];
           shan.tag -=1;
   
            if (tttt.x!=10) {
                
                [UIView animateWithDuration:0.3 animations:^{
                     tttt.x -= tttt.width+10;
                }];
               
            }else{
            
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                   
                    [UIView animateWithDuration:0.18 animations:^{
                                            tttt.x = SCREEN_WIDTH-tttt.width-10;
                                            tttt.y -= tttt.height+10;
                                        }];
                });
            }
    }
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        /**
         *  当相册列表有9张（没有添加btn） 到删除一张 到8张得时候 将添加btn添加上去
         */
        if (self.imagess.count==8) {
            
            UIButton *imageView = [UIButton buttonWithType:UIButtonTypeCustom];
            imageView.tag = 8+10000;
            
            CGFloat row = 8%4;
            CGFloat lod = 8/4;
            
            CGFloat xx = XXXDDD+(XXXDDD+WWWWW)*row;
            CGFloat yy = XXXDDD +(XXXDDD+WWWWW)*lod;
            
            imageView.frame = CGRectMake(xx, yy, WWWWW, WWWWW);
            
             [imageView setImage:[UIImage imageNamed:@"add_pic"] forState:UIControlStateNormal];
         
            [imageView addTarget:self action:@selector(AddImage) forControlEvents:UIControlEventTouchUpInside];
            
            [self.scrollView addSubview:imageView];
        }
        
    });
}
#pragma mark---点击添加相片
-(void)AddImage{
    UIAlertController *aler = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *ToPhone = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self takePhoto];
    }];
    
    UIAlertAction *ToImage = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self LocalPhoto];
    }];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    [aler addAction:ToPhone];
    [aler addAction:ToImage];
    [aler addAction:cancel];
    [self presentViewController:aler animated:YES completion:nil];
    
}
/**
 *  打开相册
 */
-(void)LocalPhoto{
    
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 delegate:self];
    imagePickerVc.SelectImagesCount = self.imagess.count;
    
   imagePickerVc.allowPickingOriginalPhoto = NO;
    imagePickerVc.allowPickingVideo = NO;
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

#pragma mark---调用相机
-(void)takePhoto{
    BOOL isCameraValid = YES;
    if(iOS7)
    {
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (authStatus != AVAuthorizationStatusAuthorized)
        {
            isCameraValid = NO;
            NSString *appName = [[NSBundle mainBundle].infoDictionary valueForKey:@"CFBundleDisplayName"];
            if (!appName) appName = [[NSBundle mainBundle].infoDictionary valueForKey:@"CFBundleName"];
            [self ShowAlertWhthTitle:@"提示" Message:[NSString stringWithFormat:@"请在%@的\"设置-隐私-相机\"选项中，\r允许%@访问你的手机相机。",[UIDevice currentDevice].model,appName] CancelButtonTitle:@"好"];
    }else{
    
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]){
        
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.sourceType = sourceType; //资源类型为照相机
        [self presentViewController:picker animated:YES completion:nil];
        
            }
        }
    }
}

#pragma mark---相册相机回调协议方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];

    if (portraitImg != nil) { //当图片不为空时显示图片并保存图片
       
        UIImage *image = [Manager imageCompressForWidth:portraitImg targetWidth:800];
         [self.imagess addObject:image];
        [self.imageDataAry addObject:UIImageJPEGRepresentation(image,0.8)];
        [self CretUi];
    }

    [picker dismissViewControllerAnimated:YES completion:nil];//关闭相册界面
}

@end